package com.example.springboot_jxc_0511.common;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_jxc_0511.common.FileUtil;
import com.example.springboot_jxc_0511.jxc.common.Constants;
import com.example.springboot_jxc_0511.jxc.entity.Product;
import com.example.springboot_jxc_0511.jxc.entity.Sale;
import com.example.springboot_jxc_0511.jxc.entity.Users;
import com.example.springboot_jxc_0511.jxc.service.IProductService;
import com.example.springboot_jxc_0511.jxc.service.ISaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gongxl
 * @since 2021-05-11
 */
@Controller
@RequestMapping
public class UploadController {
    @Value("${user.file.path}")
    private String filePath;
    /**
     * @Author GongXl
     * @Description
     * @Date 2021/5/20 14:44
     * @Param [model]
     * @return java.lang.String
     **/
    @RequestMapping("/toUpload")
    public String toUpload(Model model) {
        return "upload";
    }
    /**
     * @Author GongXl
     * @Description 单文件上传
     * @Date 2021/5/20 14:47
     * @Param [file, model]
     * @return java.lang.String
     **/
    @PostMapping("/uploadFile")
    public String upload(@RequestParam("file") MultipartFile file, Model model){
        if (file.isEmpty()){
            model.addAttribute("message", "The file is empty!");
            return "upload";
        }
        try{
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath + file.getOriginalFilename());
            Files.write(path, bytes);
            model.addAttribute("message", "succes");
        }catch (Exception e){
            e.printStackTrace();
        }
        return "upload";
    }

    /**
     * 多文件上传
     * @param request
     * @param model
     * @return
     */
    @PostMapping("/multiUpload")
    public String multiUpload(HttpServletRequest request, Model model) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        File fileTemp =  new File(filePath);
        //判断文件父目录是否存在
        if(!fileTemp.exists()){
            //不存在就创建一个
            fileTemp.mkdirs();
        }
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                model.addAttribute("message", "上传第"+i+"个文件失败。");
            }
            String fileName = file.getOriginalFilename();

            File dest = new File(filePath + fileName);
            try {
                file.transferTo(dest);
                System.out.println(dest.getAbsolutePath());
                model.addAttribute("message", "succes");
                model.addAttribute("filePath","/"+fileName);
            } catch (IOException e) {
                model.addAttribute("message", "上传异常");
            }
        }


        return "upload";
    }

    /**
     * 下载文件
     * @param fileName
     * @throws IOException
     */
    @RequestMapping(value = "/download/{fileName:.+}")
    public void download(@PathVariable String fileName) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 设置信息给客户端不解析
        String type = fileName.substring(fileName.lastIndexOf(".")+1);
        // 设置contenttype，即告诉客户端所发送的数据属于什么类型
        response.setHeader("Content-type",type);
        // 设置编码
        String hehe = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
        response.setHeader("Content-Disposition", "attachment;filename=" + hehe);
        FileUtil.download(fileName, response);
    }
}

